#include "jrpc.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))

bool test_positional_params(void)
{
    int n[] = {42, 23};
    cJSON* params = cJSON_CreateIntArray(n, ARRAY_SIZE(n));
    cJSON* id = cJSON_CreateNumber(1);
    cJSON* request = jrpc_create_request("subtract1", params, id);
    char* jsons = cJSON_PrintUnformatted(request);
    if (!jsons) {
        fprintf(stderr, "Error: %s\n", cJSON_GetErrorPtr());
        return false;
    }

    cJSON_free(params);
    cJSON_free(id);
    cJSON_free(request);

    puts(jsons);
    free(jsons);

    return true;
}

bool test_named_params(void)
{
    cJSON* params = cJSON_CreateObject();
    cJSON_AddNumberToObject(params, "subtrahend", 23);
    cJSON_AddNumberToObject(params, "minuend", 42);
    cJSON* id = cJSON_CreateNumber(1);
    cJSON* request = jrpc_create_request("subtract2", params, id);
    char* jsons = cJSON_PrintUnformatted(request);
    if (!jsons) {
        return false;
    }

    cJSON_free(params);
    cJSON_free(id);
    cJSON_free(request);

    puts(jsons);
    free(jsons);

    return true;
}

bool test_notification_with_params(void)
{
    int n[] = {1, 2, 3, 4, 5};
    cJSON* params = cJSON_CreateIntArray(n, ARRAY_SIZE(n));
    cJSON* notification = jrpc_create_request("update", params, NULL);
    char* jsons = cJSON_PrintUnformatted(notification);
    if (!jsons) {
        return false;
    }
    cJSON_free(params);
    cJSON_free(notification);

    puts(jsons);
    free(jsons);
    return true;
}

bool test_notification_without_params(void)
{
    cJSON* notification = jrpc_create_request("update", NULL, NULL);
    char* jsons = cJSON_PrintUnformatted(notification);
    if (!jsons) {
        return false;
    }
    cJSON_free(notification);

    puts(jsons);
    free(jsons);
    return true;
}

int main() {
    test_positional_params();
    test_named_params();
    test_notification_with_params();
    test_notification_without_params();

    return 0;
}